import 'package:fltools/src/utils/date_util.dart';

///字符串占位符
const String placeHolderStr = '%s';

///密码
final RegExp pwdRegExp =
    RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})');

///字符串拓展
extension StringEx on String {
  ///字符串转默认时间
  DateTime? toDateTime() {
    return defaultFormatDateStr(this);
  }

  ///密码格式是否正确
  bool isMatchPwd() {
    if (pwdRegExp.hasMatch(this)) {
      return true;
    }
    return false;
  }

  ///替换所有的字符串null
  String replaceStrNull() {
    return toLowerCase().replaceAll('null', '');
  }

  ///是否为null
  bool isNull() {
    return !isNotNullWithSpace();
  }

  ///去掉空格后是否不为空
  bool isNotNullWithSpace() {
    return isNotEmpty &&
        replaceAll('\u0020', '').isNotEmpty &&
        toLowerCase() != 'null';
  }

  ///转为整型 [radix]表示为几进制
  int toInt({int? radix}) {
    if (isNotNullWithSpace()) {
      final int? i = int.tryParse(this, radix: radix);
      return i ?? 0;
    }

    return 0;
  }

  ///转为 浮点型
  double toDouble() {
    if (isNotNullWithSpace()) {
      final double? d = double.tryParse(this);
      return d ?? 0.0;
    }
    return 0.0;
  }

  ///替换字符串中的占位符[placeHolderStr]为指定的 字符串
  String replacePlaceHolder(List<String> strs) {
    String str = '';
    final List<String> strArrays = split(placeHolderStr);
    if (strArrays.length - 1 != strs.length) {
      throw Exception('place holder 数量和字符串数量不匹配');
    }
    for (int i = 0; i < strArrays.length; i++) {
      final String s = strArrays[i];
      if (i < strs.length) {
        str += '$s${strs[i]}';
      } else {
        str += s;
      }
    }

    return str;
  }
}
